package com.chat.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.chat.security.entity.JWTLoginUser;
import com.chat.security.service.JwtTokenService;
import com.chat.system.entity.dto.UserLoginDTO;
import com.chat.system.service.IAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.chat.security.service.JwtTokenService.LOGIN_USER_KEY;

@Service
public class AuthServiceImpl implements IAuthService {
    @Autowired
    AuthenticationManager providerManager;
    @Autowired
    JwtTokenService jwtTokenService;
    @Override
    public String login(UserLoginDTO loginDTO) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginDTO.getUserName(),loginDTO.getPassword());
        final Authentication authenticate = providerManager.authenticate(usernamePasswordAuthenticationToken);

        Map<String, Object> claims = new HashMap<>();
        claims.put(LOGIN_USER_KEY, JSON.toJSONString(new JWTLoginUser(authenticate.getName())));
        return jwtTokenService.getJwtToken(claims);
    }
}
